#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import os
import sys
import platform
import multiprocessing
import serial
import time
from tools.Download import build

zos_path = ';D:\\Embedded\\cygwin\\bin\\;D:\Embedded\\gcc\\bin\\'


def usage():
    print('''
    ZeusOS版本SDK的编译命令如下:

    python zos.py [action]

    <-b> 功能描述: 编译SDK

    <-c> 功能描述: 清理已编译文件

    <-m> 功能描述: 合并下载文件

    <-dl> 功能描述: 往UE下载程序 
        参数: <PortNo.>:    串口号（例如com4)

    <-s> 功能描述: 拆分文件

    示例1, 编译SDK
    python zos.py -b

    示例2, 清理已编译文件
    python zos.py -c

    示例3, 合并固件
    python zos.py -m

    示例4, 下载固件到模组
    python zos.py -dl com3

    示例5, 拆分固件
    python zos.py -s
    
    ''')

def error():
    print('''
    \033[0;36m
    ****************************************************************************
    看到这条输出的时候,请先确认属于下面那种错误:
    
    1、执行编译命令 python zos.py -b 前,没有将Embedded 文件夹放到D盘根目录

    2、代码出现错误,请看输出日志的红色error提示,error已经提示了出错文件、行号和出错的代码，请仔细排查.
    \033[0m
    ''')
def enter_download_mode(com):
    print(com)
    dev = serial.Serial(com, 115200,timeout=1, parity=serial.PARITY_NONE, stopbits=1)
    if dev.isOpen():  # 判断串口是否打开
        print("open success")
    else :
        dev.open()
    dev.write('enter_download_mode\r\n'.encode("utf8"))

    data = dev.read(30)
    if ( "OK" in str(data)):
        print("当前已经进入二次开发模式,即将下载固件\r\n")
    else :
        dev.baudrate = 9600
        dev.write('AT\r\n'.encode("utf8"))
        data = dev.read(30)
        if ( "OK" in str(data)):
            print("当前是AT固件\r\n")
            dev.write('AT+NV=SET,STANDBY,0\r\n'.encode("utf8"))
            time.sleep(2)
            dev.write('AT+NV=SET,WDT,0\r\n'.encode("utf8"))
            time.sleep(2)
            dev.write('AT+FORCEDL\r\n'.encode("utf8"))
            time.sleep(2)
            data = dev.read(4)
            print(data)
        else    :
            print("设备连接失败\r\n")

    dev.close()
    time.sleep(3)

def main():
    argc = 1
    test_list = ['-b','-c','-m','-dl','-s','-h']
    if platform.system() == "Windows":
        os.environ['PATH'] += zos_path
    while len(sys.argv) > argc:
        if sys.argv[argc] == "-b" :
            cpu_core_num = multiprocessing.cpu_count()
            make_cmd = "make -j" + str(cpu_core_num) + " all"
            make_process = os.system(make_cmd)
            merge_cmd = 0
            if make_process >0 :
                error()
                return
            if  len(sys.argv) > argc+1:
                if sys.argv[argc+1] in test_list:
                    if sys.argv[argc+1] != '-m':
                        merge_cmd = 0
                    else :
                        merge_cmd = 1;
            if merge_cmd == 0 :
                passward = ''
                print(passward)
                build.do_pack(passward)
                print('\r\n -b固件合并完成')
        elif sys.argv[argc] == "-c" :
            make_process = os.system(r'make clean')
            if make_process >0 :
                error()
                return
        elif sys.argv[argc] == '-m':
            if  len(sys.argv) > argc+1:
                if sys.argv[argc+1] in test_list:
                    passward = ''
                else :
                    passward = sys.argv[argc+1]
                    argc +=1
            else :
                passward = ''
            print(passward)
            build.do_pack(passward)
            print('\r\n固件合并完成')
        elif sys.argv[argc] == '-dl':
            cmd_list = []
            if  len(sys.argv) > argc+1:
                if sys.argv[argc+1] in test_list:
                    print("执行下载命令，需要输入串口信息。")
                    print("例如:python zos.py -dl com3")
                    return
                else :
                    cmd_list.append(sys.argv[argc+1]);
                    if  len(sys.argv) > argc+2:
                        if sys.argv[argc+2] not in test_list:
                            cmd_list.append(sys.argv[argc+2]);
                    enter_download_mode(cmd_list[0])
                    build.do_download(cmd_list)
                    argc +=1
            else :
                print("执行下载命令，需要输入串口信息。")
                print("例如:python zos.py -dl com3")
                return
        elif sys.argv[argc] == '-s':
            
            if  len(sys.argv) > argc+1:
                if sys.argv[argc+1] in test_list:
                    passward = ''
                else :
                    passward = sys.argv[argc+1]
                    argc +=1
            else :
                passward = ''
            print(passward)
            build.do_unpack(passward)
            print('\r\n固件拆分完成')
        elif sys.argv[argc] == '-h':
            usage()
        else :
            usage();
        argc += 1
        print("***********************************************************************")
    print("操作已完成，再见")

if len(sys.argv) == 1 :
    usage()
else :
    main()


